<template>
  <div class="floor-detail">
    <div class="page-header">
      <div class="header-left">
        <el-page-header @back="goBack" :content="`${floorInfo.floor_number || ''}层详情`"></el-page-header>
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/admin/assets/BuildingList' }">空间管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/admin/assets/BuildingDetail/${floorInfo.building.building_id}` }">{{ buildingInfo.name }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ floorInfo.floor_number }}层详情</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- <div class="header-right">
        <el-button type="primary" @click="openDialog">编辑信息</el-button>
      </div> -->
    </div>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-row :gutter="20">
          <el-col :span="14">
            <el-card v-loading="loading" class="info-card">
              <div class="card-header">
                <h3>楼层基本信息</h3>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="info-item">
                    <span class="label">楼层ID：</span>
                    <span class="value">{{ floorInfo.floor_id }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="info-item">
                    <span class="label">楼层号：</span>
                    <span class="value">{{ floorInfo.floor_number }} 层</span>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="info-item">
                    <span class="label">实际标号：</span>
                    <span class="value">{{ floorInfo.actual_label }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="info-item">
                    <span class="label">层高：</span>
                    <span class="value">{{ floorInfo.height }} 米</span>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="info-item">
                    <span class="label">承重：</span>
                    <span class="value">{{ floorInfo.load_bearing }} kg/㎡</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="info-item">
                    <span class="label">创建时间：</span>
                    <span class="value">{{ floorInfo.created_at }}</span>
                  </div>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="24">
                  <div class="info-item">
                    <span class="label">功能分区描述：</span>
                    <span class="value">{{ floorInfo.function_zone_desc || '无' }}</span>
                  </div>
                </el-col>
              </el-row>

              <el-divider></el-divider>

              <el-row :gutter="20">
                <el-col :span="8">
                  <div class="statistic-item">
                    <div class="statistic-title">总房间数</div>
                    <div class="statistic-value">{{ statistics.totalRooms }}</div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="statistic-item">
                    <div class="statistic-title">已租房间</div>
                    <div class="statistic-value">{{ statistics.rentedRooms }}</div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="statistic-item">
                    <div class="statistic-title">出租率</div>
                    <div class="statistic-value">{{ statistics.occupancyRate }}%</div>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
          <el-col :span="10">
            <el-card class="equipment-card">
              <div class="card-header">
                <h3>公共设备</h3>
              </div>
              <div class="equipment-list">
                <el-table
                  :data="equipmentList"
                  border
                  style="width: 100%">
                  <el-table-column
                    prop="name"
                    label="设备名称">
                  </el-table-column>
                  <el-table-column
                    prop="count"
                    label="数量"
                    width="80">
                  </el-table-column>
                  <el-table-column
                    prop="status"
                    label="状态"
                    width="100">
                    <template #default="scope">
                      <el-tag :type="getEquipStatusType(scope.row.status)">
                        {{ getEquipStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="room-info-card" style="margin-top: 20px;">
          <!-- <div class="card-header">
            <h3>房源列表</h3>
          </div> -->
          
          <div class="card-header" style="margin-top: 20px;">
            <h3>楼层销控图</h3>
            <div class="legend">
              <div class="legend-item">
                <span class="legend-color" style="background-color: #67C23A;"></span>
                <span>空置</span>
              </div>
              <div class="legend-item">
                <span class="legend-color" style="background-color: #E6A23C;"></span>
                <span>意向</span>
              </div>
              <div class="legend-item">
                <span class="legend-color" style="background-color: #409EFF;"></span>
                <span>已租</span>
              </div>
              <div class="legend-item">
                <span class="legend-color" style="background-color: #F56C6C;"></span>
                <span>已售</span>
              </div>
              <div class="legend-item">
                <span class="legend-color" style="background-color: #909399;"></span>
                <span>不可用</span>
              </div>
            </div>
          </div>
          <div class="floor-plan-container">
            <div class="sales-control-map" v-loading="loading">
              <div class="map-content" v-if="roomList.length > 0">
                <div class="unit-grid" :style="gridStyle">
                  <div 
                    v-for="unit in roomList" 
                    :key="unit.id" 
                    class="unit-block"
                    :class="{
                      'unit-vacant': unit.status === '空置',
                      'unit-intended': unit.status === '意向',
                      'unit-rented': unit.status === '已租',
                      'unit-sold': unit.status === '已售',
                      'unit-renovating': unit.status === '装修中',
                      'unit-maintaining': unit.status === '维修中',
                      'unit-cleaning': unit.status === '待清洁',
                      'unit-unavailable': unit.status === '不可用'
                    }"
                    @click="viewRoomDetail(unit)"
                  >
                    <div class="unit-number">{{ unit.roomNumber }}</div>
                    <div class="unit-area">{{ unit.area }}㎡</div>
                    <div class="unit-status">{{ getRoomStatusText(unit.status) }}</div>
                    <div v-if="unit.company" class="unit-company">{{ unit.company }}</div>
                  </div>
                </div>
              </div>
              <div v-else class="no-data">
                <el-empty description="暂无房间数据"></el-empty>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 楼层编辑对话框 -->
    <el-dialog title="编辑楼层信息" v-model="dialogVisible" width="600px">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px">
        <el-form-item label="楼层号" prop="floor_number">
          <el-input-number v-model="editForm.floor_number" :min="1" :max="200" :disabled="true"></el-input-number>
        </el-form-item>
        <el-form-item label="实际标号" prop="actual_label">
          <el-input v-model="editForm.actual_label" placeholder="请输入实际标号(如G/F1/M)"></el-input>
        </el-form-item>
        <el-form-item label="层高(米)" prop="height">
          <el-input-number v-model="editForm.height" :min="0" :precision="2" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="承重(kg/㎡)" prop="load_bearing">
          <el-input-number v-model="editForm.load_bearing" :min="0" :precision="2" :step="10"></el-input-number>
        </el-form-item>
        <el-form-item label="功能分区描述" prop="function_zone_desc">
          <el-input type="textarea" v-model="editForm.function_zone_desc" placeholder="请输入功能分区描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 单元详情弹窗 -->
    <el-dialog title="房间详情" v-model="unitDialogVisible" width="700px">
      <div v-if="selectedUnit" class="unit-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="房间号">{{ selectedUnit.roomNumber }}</el-descriptions-item>
          <el-descriptions-item label="面积">{{ selectedUnit.area }}㎡</el-descriptions-item>
          <el-descriptions-item label="类型">{{ selectedUnit.type }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getRoomStatusType(selectedUnit.status)">{{ getRoomStatusText(selectedUnit.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="租户" :span="2">{{ selectedUnit.company || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="unitDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="goToUnitDetail">查看详情</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getFloorDetail, getFloorRooms, getFloorPublicDevices, getUnitDetail } from '@/api/assets.js'
import { ref, computed } from 'vue'

export default {
  name: 'FloorDetail',
  data() {
    return {
      loading: false,
      floorId: '',
      buildingInfo: {
        id: '',
        name: ''
      },
      floorInfo: {
        floor_id: '',
        building: {
          building_id: '',
          name: ''
        },
        floor_number: 0,
        actual_label: '',
        height: 0,
        load_bearing: 0,
        function_zone_desc: '',
        created_at: '',
        updated_at: '',
        floorPlanUrl: '' // 前端自定义属性
      },
      statistics: {
        totalRooms: 0,
        rentedRooms: 0,
        occupancyRate: 0
      },
      roomList: [],
      equipmentList: [],
      dialogVisible: false,
      uploadDialogVisible: false,
      unitDialogVisible: false,
      selectedUnit: null,
      editForm: {
        floor_id: '',
        building_id: '',
        floor_number: 0,
        actual_label: '',
        height: 0,
        load_bearing: 0,
        function_zone_desc: ''
      },
      rules: {
        actual_label: [
          { required: true, message: '请输入实际标号', trigger: 'blur' }
        ],
        height: [
          { required: true, message: '请输入层高', trigger: 'blur' }
        ],
        load_bearing: [
          { required: true, message: '请输入承重', trigger: 'blur' }
        ],
        function_zone_desc: [
          { required: true, message: '请输入功能分区描述', trigger: 'blur' }
        ]
      },
      gridStyle: {
        gridTemplateColumns: 'repeat(4, 1fr)',
        gridGap: '15px',
      }
    }
  },
  created() {
    this.floorId = this.$route.params.id
    this.fetchFloorInfo()
    this.fetchRoomList()
    this.fetchEquipmentList()
  },
  methods: {
    // 获取楼层信息
    async fetchFloorInfo() {
      this.loading = true
      try {
        const response = await getFloorDetail(this.floorId)
        if (response.data.code === 200) {
          this.floorInfo = response.data.data
          this.buildingInfo = {
            id: this.floorInfo.building.building_id,
            name: this.floorInfo.building.name
          }
        }
      } catch (error) {
        this.$message.error('获取楼层详情失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    // 获取房间列表
    async fetchRoomList() {
      try {
        const response = await getFloorRooms(this.floorId)
        if (response.data.code === 200) {
          this.roomList = response.data.data
          this.calculateStatistics()
        }
      } catch (error) {
        this.$message.error('获取房间列表失败')
        console.error(error)
      }
    },
    // 获取设备列表
    async fetchEquipmentList() {
      try {
        const response = await getFloorPublicDevices(this.floorId)
        if (response.data.code === 200) {
          this.equipmentList = response.data.data
        }
      } catch (error) {
        this.$message.error('获取楼层公共设备列表失败')
        console.error(error)
      }
    },
    // 计算统计数据
    calculateStatistics() {
      const totalRooms = this.roomList.length
      const rentedRooms = this.roomList.filter(room => room.status === '已租').length
      this.statistics = {
        totalRooms,
        rentedRooms,
        occupancyRate: totalRooms > 0 ? ((rentedRooms / totalRooms) * 100).toFixed(1) : 0
      }
    },
    // 获取房间状态对应的标签类型
    getRoomStatusType(status) {
      switch(status) {
        case '空置': return 'success'
        case '意向': return 'warning'
        case '已租': return 'primary'
        case '已售': return 'danger'
        case '装修中': return 'info'
        case '维修中': return 'info'
        case '待清洁': return 'info'
        case '不可用': return 'info'
        default: return 'info'
      }
    },
    // 获取房间状态显示文字
    getRoomStatusText(status) {
      return status || '未知'
    },
    // 获取设备状态对应的标签类型
    getEquipStatusType(status) {
      switch(status) {
        case '正常': return 'success'
        case '故障': return 'danger'
        case '维修中': return 'warning'
        case '停用': return 'info'
        default: return 'info'
      }
    },
    // 获取设备状态显示文字
    getEquipStatusText(status) {
      return status || '未知'
    },
    // 查看房间详情
    viewRoomDetail(room) {
      this.selectedUnit = room
      this.unitDialogVisible = true
    },
    // 跳转到房间详情页
    goToUnitDetail() {
      if (this.selectedUnit && this.selectedUnit.id) {
        this.$router.push(`/admin/assets/UnitDetail/${this.selectedUnit.id}`)
      }
      this.unitDialogVisible = false
    },
    // 返回上一页
    goBack() {
      this.$router.push(`/admin/assets/BuildingDetail/${this.floorInfo.building.building_id}`)
    },
    // 打开编辑对话框
    openDialog() {
      this.editForm = JSON.parse(JSON.stringify(this.floorInfo))
      this.dialogVisible = true
    },
    // 打开上传平面图对话框
    uploadFloorPlan() {
      this.uploadDialogVisible = true
    },
    // 提交上传
    submitUpload() {
      this.$message.info('平面图上传功能暂未实现')
      this.uploadDialogVisible = false
    },
    // 提交编辑表单
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // TODO: 调用API更新楼层信息
          this.$message.success('编辑成功')
          this.dialogVisible = false
          // 更新本地数据
          Object.assign(this.floorInfo, this.editForm)
        }
      })
    }
  }
}
</script>

<style scoped>
.floor-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.breadcrumb {
  margin-top: 10px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.info-item {
  margin-bottom: 18px;
  display: flex;
  align-items: center;
}

.label {
  color: #909399;
  font-size: 16px;
  font-weight: bold;
  width: 130px;
  text-align: right;
  padding-right: 12px;
  flex-shrink: 0;
}

.value {
  color: #303133;
  font-size: 15px;
  margin-left: 0;
  font-weight: 500;
  flex-grow: 1;
}

.statistic-item {
  text-align: center;
  padding: 10px 0;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.statistic-title {
  font-size: 14px;
  color: #909399;
}

.statistic-value {
  font-size: 22px;
  color: #409EFF;
  font-weight: bold;
}

.room-table {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.table-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.floor-plan-card {
  margin-bottom: 20px;
  height: auto;
}

.legend {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.legend-color {
  display: inline-block;
  width: 14px;
  height: 14px;
  border-radius: 2px;
  margin-right: 5px;
}

.floor-plan-container {
  position: relative;
  min-height: 400px;
}

.sales-control-map {
  margin-top: 20px;
  position: relative;
  height: 500px;
  overflow-y: auto;
}

.map-content {
  padding: 15px;
}

.unit-grid {
  display: grid;
  grid-gap: 15px;
}

.unit-block {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}

.unit-block:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.unit-vacant {
  background-color: rgba(103, 194, 58, 0.1);
  border-left: 4px solid #67C23A;
}

.unit-intended {
  background-color: rgba(230, 162, 60, 0.1);
  border-left: 4px solid #E6A23C;
}

.unit-rented {
  background-color: rgba(64, 158, 255, 0.1);
  border-left: 4px solid #409EFF;
}

.unit-sold {
  background-color: rgba(245, 108, 108, 0.1);
  border-left: 4px solid #F56C6C;
}

.unit-renovating,
.unit-maintaining,
.unit-cleaning {
  background-color: rgba(144, 147, 153, 0.1);
  border-left: 4px solid #909399;
}

.unit-unavailable {
  background-color: rgba(144, 147, 153, 0.1);
  border-left: 4px solid #909399;
  opacity: 0.7;
}

.unit-number {
  font-size: 15px;
  font-weight: bold;
  color: #303133;
  position: absolute;
  top: 10px;
  left: 10px;
}

.unit-area {
  font-size: 13px;
  color: #606266;
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.unit-status {
  font-size: 13px;
  font-weight: 500;
  position: absolute;
  bottom: 10px;
  left: 10px;
}

.unit-company {
  font-size: 12px;
  color: #909399;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.equipment-card {
  height: 380px;
}

.equipment-list {
  margin-top: 10px;
  flex: 1;
  overflow-y: auto;
}

.upload-container {
  text-align: center;
}

/* 单元详情弹窗样式 */
.unit-detail {
  padding: 10px;
}

.info-card,
.equipment-card {
  height: 380px;
}

.equipment-card :deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
</style> 